<template>
  <div v-if="dialogShow" v-loading="loading" :element-loading-text="loadingText">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">产品上样推荐配置</el-breadcrumb-item>
        <el-breadcrumb-item>{{ formData.id ? (flag === 'edit' ? '编辑' : '详情') : '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click="handleBack">返回</el-button>
      </div>
    </div>
    <div class="qup-title-box">
      <span class="border" /><span>推荐方案信息</span>
    </div>
    <div style="margin-bottom: 10px">
      <el-button v-if="!isEdit && flag !== 'detail'" type="primary" size="mini" @click="editForm">编辑</el-button>
      <div v-if="isEdit">
        <el-button type="primary" size="mini" @click="handleSaveInfo">保存</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </div>
    <el-form ref="ruleForm" :model="formData" size="mini" :rules="rules" label-width="140px">
      <el-row class="form_item_height">
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="所属专区:" prop="configSpace">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.styleName }}</span>
            <input-with-dialog
              v-else
              v-model="formData.configStyle"
              :props="{label:'styleName',value:'id'}"
              param-field="keyWord"
              request-method="post"
              :multiple="false"
              :focus-query="true"
              :config="styleConfig"
              @change="styleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="所属空间:" prop="configSpace">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.spaceName }}</span>
            <input-with-dialog
              v-else
              v-model="formData.configSpace"
              :props="{label:'spaceName',value:'spaceCode'}"
              param-field="keyWord"
              request-method="post"
              :multiple="false"
              :focus-query="true"
              :config="spaceConfig"
              @change="spaceChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="上样推荐方案:" prop="recommendProgram">
            <span v-if="flag === 'detail' || !isEdit">{{ formaterData(recommendProgramList, formData.recommendProgram) }}</span>
            <c-dict-select v-else v-model="formData.recommendProgram" dict-type-code="RECOMMEND_PROGRAM" placeholder="上样推荐方案" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="专区划分:" prop="divide">
            <span v-if="flag === 'detail' || !isEdit">{{ formaterData(divideOptions, formData.divide) }}</span>
            <c-dict-select v-else v-model="formData.divide" multiple dict-type-code="ZONE_DIVISION" placeholder="专区划分" @change="changeMultiple" />
          </el-form-item>
        </el-col>

        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最小面积:" prop="suitMinarea">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.suitMinarea }}</span>
            <el-input v-else v-model.number="formData.suitMinarea" placeholder="请输入适用最小面积" @change="checkArea('suitMinarea','suitMaxarea',formData.suitMinarea,'>')" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最大面积:" prop="suitMaxarea">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.suitMaxarea }}</span>
            <el-input v-else v-model.number="formData.suitMaxarea" placeholder="请输入适用最大面积" @change="checkArea('suitMaxarea','suitMinarea',formData.suitMaxarea,'<')" />
          </el-form-item>
        </el-col>

        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="款式最小数量:" prop="styleMinnum">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.styleMinnum }}</span>
            <el-input v-else v-model.number="formData.styleMinnum" placeholder="请输入适用最小数量" @change="checkArea('styleMinnum','styleMaxnum',formData.styleMinnum,'>')" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="款式最大数量:" prop="styleMaxnum">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.styleMaxnum }}</span>
            <el-input v-else v-model.number="formData.styleMaxnum" placeholder="请输入适用最大数量" @change="checkArea('styleMaxnum','styleMinnum',formData.styleMaxnum,'<')" />
          </el-form-item>
        </el-col>

        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="档案适用最小面积:" prop="archivesMinarea">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.archivesMinarea }}</span>
            <el-input v-else v-model.number="formData.archivesMinarea" placeholder="档案适用最小面积" @change="checkArea('archivesMinarea','archivesMaxarea',formData.archivesMinarea,'>')" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="档案适用最大面积:" prop="archivesMaxarea">
            <span v-if="flag === 'detail' || !isEdit">{{ formData.archivesMaxarea }}</span>
            <el-input v-else v-model.number="formData.archivesMaxarea" placeholder="档案适用最大面积" @change="checkArea('archivesMaxarea','archivesMinarea',formData.archivesMaxarea,'<')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <div class="qup-title-box">
        <span class="border" /><span>方案明细清单</span>
      </div>
      <div>
        <search-form
          :search-config="searchConfig"
          :label-width="80"
          style="margin-bottom: 10px"
          @clear="clearSearch"
          @search="handleSearch"
        />
      </div>
      <div v-if="flag !== 'detail'" class="btn-box">
        <template>
          <el-button size="mini" type="primary" @click="addRow">新增</el-button>
          <el-button size="mini" type="primary" @click="delRow">删行</el-button>
          <!-- <el-button v-if="showPageFlag" size="mini" type="primary" @click="handleImport">导入</el-button> -->
          <!-- <el-button v-if="showPageFlag" size="mini" type="primary" @click="handleExport">导出</el-button> -->
          <el-button v-if="!showPageFlag" size="mini" type="primary" @click="saveTableData">保存</el-button>
          <el-button v-if="!showPageFlag" size="mini" type="primary" @click="cancelEditTable">取消</el-button>
        </template>
      </div>
      <el-table
        ref="refTable"
        v-loading="tableLoading"
        element-loading-text="加载中"
        :data="tableData"
        highlight-current-row
        max-height="400"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%; margin-top: 20px"
        @selection-change="selectionChangeHandle"
      >
        <el-table-column v-if="flag !== 'detail'" type="selection" width="55" :selectable="selectable" />
        <el-table-column prop="categoryCode" label="品类" min-width="80" show-overflow-tooltip>
          <template slot="header">
            <span style="color: red">*</span>品类
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.categoryName }}</span>
            <input-with-dialog
              v-else
              v-model="scope.row.category"
              :props="categoryProp"
              :config="categoryConfig"
              @change="v=>categoryChange(v, scope.row,scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="modelCode" label="型号" min-width="100">
          <template slot="header">
            <span style="color: red">*</span>型号
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.modelName }}</span>
            <input-with-dialog
              v-else
              v-model="scope.row.modelArr"
              :props="{label:'name',value:'code'}"
              :multiple="true"
              :config="modelConfig"
              @change="modelChange(scope.row, scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="编码" min-width="100">
          <template v-if="scope.row.seriesList" slot-scope="scope">
            <el-select
              v-model="scope.row.productCode"
              placeholder="请选择产品编码"
              style="width: 100%"
            >
              <el-option
                v-for="item in scope.row.seriesList"
                :key="item.id"
                :label="item.productName"
                :value="item.productCode"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="seriesName" label="系列" min-width="100" show-overflow-tooltip />
        <el-table-column prop="proPosition" label="产品定位" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ formaterData(seriesNameList, scope.row.proPosition) }}</span>
            <c-dict-select v-else v-model="scope.row.proPosition" dict-type-code="SERIES_NAME" placeholder="产品定位" />
          </template>
        </el-table-column>
        <el-table-column prop="recommendNum" label="推荐数量" min-width="100">
          <template slot="header">
            <span style="color: red">*</span>推荐数量
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.recommendNum }}</span>
            <el-input v-else v-model.number="scope.row.recommendNum" type="number" size="mini" min="1" @blur="handelBlur(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="functionSpace" label="功能空间" min-width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ formaterData(functionSpaceList, scope.row.functionSpace) }}</span>
            <c-dict-select v-else v-model="scope.row.functionSpace" multiple dict-type-code="SAMPLE_FUNCTION_SPACE" placeholder="功能空间" />
          </template>
        </el-table-column>
        <el-table-column prop="assortEndProductProgramme" label="配套成品方案" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ formaterData(assortProList, scope.row.assortEndProductProgramme) }}</span>
            <c-dict-select v-else v-model="scope.row.assortEndProductProgramme" dict-type-code="ASSORT_PROGRAMME" placeholder="配套成品方案" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.remark }}</span>
            <el-input v-else v-model="scope.row.remark" size="mini" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-box">
        <div v-if="showPageFlag" class="pagination-container">
          <el-pagination
            :current-page.sync="tableInfo.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="sizes, prev, pager, next, slot"
            :total="allTotal === 0 ? tableInfo.total : allTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <span class="el-pagination__jump">前往
              <el-input-number
                v-model="jumpPage"
                :controls="false"
                :min="1"
                @blur="showEnter"
                @keyup.enter.native="showEnter"
              />页</span>
          </el-pagination>
          <div v-show="tableInfo.total <= tableInfo.rows" class="pagination-info">当前显示
            <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
            <span class="total"> {{ tableData.length }} </span> 条记录
          </div>
          <div v-show="tableInfo.total > tableInfo.rows" class="pagination-info">当前显示
            <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
            <span :class="[allTotal === 0 && tableInfo.total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && tableInfo.total !== 0 ? tableInfo.total-1 +'+': allTotal }}  </span> 条记录
          </div>
        </div>
      </div>
      <div>
        <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
        <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
      </div>
    </div>
  </div>
</template>

<script>
import { formaterData } from '@/utils'
import { getProRecommend, saveProRecommend, getRecommendDetail, delRecommendDetail, saveRecommendDetail } from '@/api/basicData'
import { getDictByPatchType } from '@/api/dataDict'
import { queryCategoryData, searchProductCodes } from '@/api/proConfig'
export default {
  name: 'AddProRecommend',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      formaterData,
      changeProductCode: [],
      exportVisible: false,
      importVisible: false,
      loading: false,
      loadingText: '',
      flag: '',
      showPageFlag: true,
      isEdit: false,
      tableLoading: false,
      oldFormInfo: {},
      recommendProgramList: [],
      seriesNameList: [],
      functionSpaceList: [],
      assortProList: [],
      divideOptions: [],
      enableList: [
        { dictName: '启用', dictCode: 1 },
        { dictName: '停用', dictCode: 0 }
      ],
      searchConfig: [
        {
          label: '型号',
          prop: 'modelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/productModel/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '型号',
            interfacePath: '/select-service/api/v1/productModel/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' },
              {
                prop: 'saleSeriesCode',
                title: '系列编码'
              },
              {
                prop: 'saleSeriesName',
                title: '系列名称'
              }],
            pageFlag: true
          }
        },
        {
          label: '品类',
          prop: 'categoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/productCategory/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
            // apiHeader: { 'permission-code': 'role_transfer_service', 'Permission-App': 'order-center' }
          },
          dialogConfig: {
            title: '品类',
            interfacePath: '/select-service/api/v1/productCategory/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        }
      ],
      selectedRows: [],
      otherFilters: [],
      tableConfig: {
        pageFlag: true,
        hideFuncBar: true,
        setting: []
      },
      formData: {
        configSpace: [],
        enable: 1
      },
      rules: {
        configSpace: [{ required: true, message: '请选择所属空间/专区' }]
      },
      dataId: [],
      tableData: [],
      tableInfo: {
        currentPage: 1,
        total: '',
        rows: 10
      },
      jumpPage: '',
      allTotal: 0,
      categoryProp: { label: 'name', value: 'code' },
      styleConfig: {
        title: '所属专区',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configStyle/page`,
        setting: [
          {
            prop: 'styleCode',
            title: '编码'
          },
          {
            prop: 'styleName',
            title: '名称'
          }
        ],
        filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' }]
      },
      spaceConfig: {
        title: '所属空间',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`,
        setting: [
          {
            prop: 'spaceCode',
            title: '编码'
          },
          {
            prop: 'spaceName',
            title: '名称'
          }
        ],
        filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' },
          { 'id': 'areaCode', 'property': 'areaCode', 'operator': 'in', 'value': '[Q014, Q015]' }]
      },
      categoryConfig: {
        title: '品类',
        interfacePath: `/select-service/api/v1/productCategory/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          },
          {
            prop: 'parentCode',
            title: '上级品类编码'
          },
          {
            prop: 'parentName',
            title: '上级品类名称'
          }
        ]
      },
      modelConfig: {
        title: '型号',
        interfacePath: `/select-service/api/v1/productModel/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          },
          {
            prop: 'saleSeriesCode',
            title: '系列编码'
          },
          {
            prop: 'saleSeriesName',
            title: '系列名称'
          }
        ]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '产品上样推荐方案明细清单',
        dataApi: '/slm-admin/api/v1/configSampleDetail/export?type=0',
        selectedRows: this.selectedRows,
        paramsRaw: {},
        filtersRaw: this.dataId,
        queryField: 'id'
      },
      {
        code: 'exportTemplate',
        name: '产品上样推荐方案明细清单模板',
        async: false,
        templateMethod: 'post',
        templateApi: '/slm-admin/api/v1/configSampleDetail/export?type=1'
      }]
    },
    fileImportConfig() {
      return [{
        code: 'import',
        name: '新增产品上样推荐方案明细清单',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleDetail/importExcel?type=1'
      },
      {
        code: 'importUpdate',
        name: '修改产品上样推荐方案明细清单',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleDetail/importExcel?type=0'
      }]
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['RECOMMEND_PROGRAM', 'SERIES_NAME', 'SAMPLE_FUNCTION_SPACE', 'ASSORT_PROGRAMME', 'ZONE_DIVISION']).then(res => {
      this.recommendProgramList = res.RECOMMEND_PROGRAM
      this.seriesNameList = res.SERIES_NAME
      this.functionSpaceList = res.SAMPLE_FUNCTION_SPACE
      this.assortProList = res.ASSORT_PROGRAMME
      this.divideOptions = res.ZONE_DIVISION
    })
    if (this.detailData.id) {
      this.loading = false
      this.loadingText = '加载中'
      this.flag = this.detailData.flag
      await this.getFormData()
      this.allTotal = 0
      this.getTableData(1, 10, false, this.otherFilters)
    }
  },
  methods: {
    changeMultiple(data) {
      if (!data || data.length === 0) return
      if (data.includes('A') && data.length > 1) {
        this.$message.warning('样板间和其他专区不可同时选择')
        this.formData.divide = []
      }
    },
    // 获取品类
    async getCategoryData(arr) {
      const codes = '[' + arr.join(',') + ']'
      const filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      return await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          return res.data.records
        }
      })
    },
    // 表格搜索
    async handleSearch(data) {
      const noIdList = this.tableData.filter(item => !item.id)
      if (noIdList.length) {
        this.$message.warning('当前存在未保存数据，请保存数据后再进行查询')
        return
      }
      const arr = JSON.parse(JSON.stringify(data.filtersRaw))
      if (arr.length) {
        let parentCode = ''
        const plCodeArr = arr.filter(item => item.property === 'categoryCode')
        if (plCodeArr.length) {
          const plCode = [plCodeArr[0].value]
          const pl = await this.getCategoryData(plCode)
          if (pl[0].parentCode) {
            parentCode = pl[0].parentCode
          } else {
            parentCode = pl[0].code
          }
        }
        arr.forEach(item => {
          if (item.property === 'categoryCode') {
            item.value = parentCode
          }
        })
      }
      this.otherFilters = [...arr]
      this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
    },
    // 清空搜索
    clearSearch() {
      this.otherFilters = []
    },
    // 获取表单数据
    async getFormData() {
      this.loading = true
      await getProRecommend(this.detailData.id).then(res => {
        if (res.success) {
          this.formData = res.data
          const space = [{ label: this.formData.spaceName, value: this.formData.spaceCode }]
          this.$set(this.formData, 'configSpace', space)
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 获取表格数据
    async getTableData(page, rows, onlyCountFlag, otherFilters) {
      this.tableLoading = true
      this.dataId = [{ 'id': 'configSampleRecommendId', 'property': 'configSampleRecommendId', 'operator': '=', 'value': this.formData.id }]
      const arr = [...this.dataId, ...otherFilters]
      const dataForm = new FormData()
      dataForm.append('page', page)
      dataForm.append('rows', rows)
      dataForm.append('pageFlag', true)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', JSON.stringify(arr))
      await getRecommendDetail(dataForm).then(res => {
        if (res.success) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.tableData.forEach(item => {
              const category = [{ label: item.categoryName, value: item.categoryCode }]
              const modelArr = [{ label: item.modelName, value: item.modelCode }]
              this.$set(item, 'category', category)
              this.$set(item, 'modelArr', modelArr)
            })
            this.tableInfo.total = res.data.total
            this.tableInfo.currentPage = res.data.page
            if (this.tableInfo.total <= page * rows) {
              this.allTotal = this.tableInfo.total
            }
          } else {
            this.allTotal = res.data.total
            this.tableInfo.total = res.data.total
            this.tableInfo.currentPage = res.data.page
          }
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    selectable(row) {
      if (!this.showPageFlag) {
        if (row.id) {
          return false
        }
        return true
      }
      return true
    },
    // 编辑表单
    editForm() {
      this.oldFormInfo = JSON.parse(JSON.stringify(this.formData))
      const space = [{ label: this.formData.spaceName, value: this.formData.spaceCode }]
      this.$set(this.formData, 'configSpace', space)
      const style = [{ label: this.formData.styleName, value: this.formData.configStyleId }]
      this.$set(this.formData, 'configStyle', style)
      this.$set(this.formData, 'divide', (this.oldFormInfo.divide && this.oldFormInfo.divide.split(',')) || [])

      this.isEdit = true
    },
    // 选择专区
    styleChange(row) {
      if (row && row.length) {
        this.formData.configStyleId = row[0].id
        return
      }
      this.formData.configStyleId = ''
    },
    // 选择空间
    spaceChange(row) {
      if (row && row.length) {
        this.formData.configSpaceId = row[0].id
        return
      }
      this.formData.configSpaceId = ''
    },
    checkArea(param1, param2, value, operator) {
      const area = value
      if (isNaN(area) || area < 0 || (area % 1 !== 0)) {
        this.$message.warning('请输入大于或等于0的整数')
        this.formData[param1] = ''
        return
      }
      if (operator === '>' && value > this.formData[param2]) {
        this.$message.warning(`不可大于适用最大适用数，请重新输入`)
        value = ''
      }
      if (operator === '<' && value < this.formData[param2]) {
        this.$message.warning(`不可小于适用最小适用数，请重新输入`)
        value = ''
      }
    },
    // 选择品类
    categoryChange(v, row, index) {
      let categoryCode = v[0].code
      let categoryName = v[0].name
      // let categoryProp = { label: 'name', value: 'code' }
      if (v[0].parentCode) {
        // categoryProp = { label: 'parentName', value: 'parentCode' }
        categoryCode = v[0].parentCode
        categoryName = v[0].parentName
      }
      // this.categoryProp = categoryProp
      // const modelCode = row.modelCode
      // const flag = this.tableData.filter(item => ((item.categoryCode.length && item.categoryCode === categoryCode) && (item.modelCode.length && item.modelCode === modelCode)))
      // if (flag.length > 0) {
      //   this.$message.warning(`品类${row.categoryName}对应的型号${modelCode}已存在，请重新选择`)
      //   row.categoryCode = ''
      //   row.categoryName = ''
      //   // row.seriesCode = ''
      //   // row.seriesName = ''
      //   row.category = []
      //   return
      // }
      this.$set(row, 'category', [{ label: categoryName, value: categoryCode }])
      row.categoryCode = categoryCode
      row.categoryName = categoryName
      this.handleSearchProCode(row.categoryCode, row.modelCode)
    },
    // 选择型号
    modelChange(row, index) {
      const modelCodeArr = JSON.parse(JSON.stringify(row.modelArr))
      const oldModelIndex = row.modelArr.findIndex(item => item.name === row.modelName)
      const oldModel = row.modelArr.filter(item => item.name === row.modelName)
      if (oldModelIndex !== -1) {
        modelCodeArr.splice(oldModelIndex, 1)
      }
      const tmpArr = []
      modelCodeArr.forEach(model => {
        const obj = {
          categoryCode: row.categoryCode,
          categoryName: row.categoryName,
          modelCode: model.code,
          modelName: model.name,
          seriesCode: model.saleSeriesCode,
          seriesName: model.saleSeriesName,
          proPosition: row.proPosition || '',
          functionSpace: row.functionSpace || '',
          assortEndProductProgramme: row.assortEndProductProgramme || '',
          recommendNum: 1,
          category: [{ label: row.categoryName, value: row.categoryCode }],
          modelArr: [{ label: model.name, value: model.code }]
        }
        tmpArr.push(obj)
      })
      // let arr1 = []
      let arr2 = []
      // arr1 = this.tableData.filter((row, rowIndex) => {
      //   const dataIndex = tmpArr.findIndex(v => ((row.categoryCode.length && (v.categoryCode === row.categoryCode)) && (row.modelCode.length && (v.modelCode === row.modelCode))))
      //   return dataIndex !== -1
      // })
      arr2 = tmpArr.filter(row => {
        const index = this.tableData.findIndex(v => ((row.categoryCode.length && (v.categoryCode === row.categoryCode)) && (row.modelCode.length && (v.modelCode === row.modelCode))))
        return index === -1
      })
      // if (arr1.length) {
      //   const msgArr = arr1.map(item => item.modelName)
      //   this.$message.warning(`品类${row.categoryName}对应的型号${msgArr.toString()}已存在，请重新选择`)
      //   if (!arr2.length) {
      //     row.modelArr = []
      //     row.modelName = ''
      //     row.modelCode = ''
      //     row.seriesCode = ''
      //     row.seriesName = ''
      //   }
      // }
      if (oldModel.length) {
        const obj = {
          categoryCode: row.categoryCode,
          categoryName: row.categoryName,
          modelCode: oldModel[0].code,
          modelName: oldModel[0].name,
          seriesCode: oldModel[0].saleSeriesCode,
          seriesName: oldModel[0].saleSeriesName,
          proPosition: row.proPosition || '',
          functionSpace: row.functionSpace || '',
          assortEndProductProgramme: row.assortEndProductProgramme || '',
          recommendNum: 1,
          category: [{ label: row.categoryName, value: row.categoryCode }],
          modelArr: [{ label: oldModel[0].name, value: oldModel[0].code }]
        }
        this.$set(this.tableData, index, obj)
      }
      if (arr2.length) {
        if (oldModel.length) {
          arr2.forEach(a => {
            this.tableData.splice(index, 0, a)
          })
        } else {
          this.$set(this.tableData, index, arr2[0])
          arr2.splice(0, 1)
          if (arr2.length) {
            arr2.forEach(a => {
              this.tableData.splice(index, 0, a)
            })
          }
        }
      }
      this.handleSearchProCode(this.tableData[index].categoryCode, this.tableData[index].modelCode)
    },
    // 产品编码根据品类型号主数据获取对应信息
    async   handleSearchProCode(categoryCode, modelCode) {
      if (!categoryCode || !modelCode) return
      const index = this.tableData.findIndex(v => (v.categoryCode === categoryCode && v.modelCode === modelCode))
      if (index === -1) return
      const filterRow = [{ 'id': 'prodModelCode', 'property': 'prodModelCode', 'operator': '=', 'value': this.tableData[index].modelCode },
        { 'id': 'productCategoryCode', 'property': 'productCategoryCode', 'operator': '=', 'value': this.tableData[index].categoryCode },
        { 'id': 'isSaleProduct', 'property': 'isSaleProduct', 'operator': '=', 'value': '1' }
      ]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)

      dataForm.append('filtersRaw', JSON.stringify(filterRow))

      await searchProductCodes(dataForm).then(res => {
        // 获取产品编码
        const list = res.data.records.filter(v => v.customizeType === 'NORM' && v.isSaleProduct === 1)
        this.$set(this.tableData[index], 'seriesList', list)
        // this.$set(this.tableData[index], 'productCode', list.join(','))
      })
    },
    // 新增
    addRow() {
      this.showPageFlag = false
      const obj = {
        categoryCode: '',
        categoryName: '',
        modelCode: '',
        modelName: '',
        seriesCode: '',
        seriesName: '',
        proPosition: '',
        functionSpace: '',
        assortEndProductProgramme: '',
        recommendNum: 1,
        category: [],
        modelArr: []
      }
      this.tableData.unshift(obj)
    },
    // 取消表格编辑
    cancelEditTable() {
      this.showPageFlag = true
      this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 删除
    delRow() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (!this.showPageFlag) {
          if (this.tableData.length === this.selectedRows.length) {
            this.tableData = []
            this.selectedRows = []
            this.$refs.refTable.clearSelection()
            return
          }
          const tmpData = this.tableData.filter(row => {
            const index = this.selectedRows.findIndex(v => (v.categoryCode === row.categoryCode && v.modelCode === row.modelCode))
            return index === -1
          })
          this.tableData = tmpData
          this.selectedRows = []
          this.$refs.refTable.clearSelection()
          return
        }
        const ids = this.selectedRows.map(item => item.id)
        delRecommendDetail(ids).then(res => {
          if (res.success) {
            this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
            this.selectedRows = []
            this.$refs.refTable.clearSelection()
          }
        })
      })
    },
    // 修改数量
    handelBlur(row) {
      const num = Number(row.recommendNum)
      if (isNaN(num) || num < 1 || (num % 1 !== 0) || num > 99) {
        row.recommendNum = 1
        this.$message.warning('请输入1~99的整数')
      }
    },
    // 导入
    handleImport() {
      // const arr = this.tableData.filter(item => !item.id)
      // if (arr.length) {
      //   this.$confirm('您有未保存的表格，是否放弃保存并进行导入?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.importVisible = true
      //   })
      // } else {
      this.importVisible = true
      // }
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 导入成功回调
    handleImportSuccess() {
      this.getTableData(1, 10, false, this.otherFilters)
    },
    // 取消表单编辑
    cancel() {
      this.formData = JSON.parse(JSON.stringify(this.oldFormInfo))
      this.isEdit = false
      this.$refs.ruleForm.clearValidate()
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.tableInfo.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.tableInfo.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.tableInfo.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      if (this.addEditFlag === true) {
        this.$message.warning('当前处于修改状态，请保存或取消后再跳页')
        return false
      }
      this.jumpPage = currentPage
      this.tableInfo.currentPage = currentPage
      this.getTableData(this.tableInfo.currentPage, this.tableInfo.rows, false, this.otherFilters)
    },
    // 切换页显示条数
    handleSizeChange(size) {
      this.tableInfo.rows = size
      this.jumpToFirstPage()
      this.getTableData(this.tableInfo.currentPage, size, false, this.otherFilters)
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.tableInfo.currentPage
      if (val) {
        page = val
      }
      this.getTableData(page, this.tableInfo.rows, true, this.otherFilters)
      // this.$nextTick(() => {
      //   this.getTableData(page, this.tableInfo.rows, false)
      // })
    },
    // 返回
    handleBack() {
      this.dialogShow = false
      this.clearForm()
      this.$emit('goBack')
    },
    // 清空表单
    clearForm(done) {
      this.formData = {}
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 保存表单数据
    handleSaveInfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.formData.suitMinarea || this.formData.suitMaxarea) {
            if (Number(this.formData.suitMinarea) > Number(this.formData.suitMaxarea)) {
              this.$message.warning('适用最小面积不可大于适用最大面积')
              return
            }
          }
          const flag = this.tableData.filter(item => !item.categoryCode.length || !item.modelCode.length)
          if (flag.length > 0) {
            this.$message.warning('请完善表格数据')
            return
          }
          this.loading = true
          this.loadingText = '系统加载中'
          this.$set(this.formData, 'divide', (this.formData.divide && this.formData.divide.join(',')) || '')
          saveProRecommend(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.isEdit = false
              this.getFormData()
            }
            this.loading = false
            this.loadingText = ''
          }).catch(() => {
            this.loading = false
            this.loadingText = ''
          })
        }
      })
    },
    // 保存表格数据
    saveTableData() {
      if (!this.tableData.length) {
        this.$message.warning('请添加方案明细清单')
        return
      }
      const arr = this.tableData.filter(item => !item.id)
      if (!arr.length) {
        this.$message.warning('请新增方案明细清单数据后保存')
        return
      }
      const flag = this.tableData.filter(item => !item.categoryCode.length || !item.modelCode.length)
      if (flag.length > 0) {
        this.$message.warning('请完善表格数据')
        return
      }
      this.tableLoading = true
      arr.forEach(item => {
        item.configSampleRecommendId = this.formData.id
        item.functionSpace = (item.functionSpace && item.functionSpace.length > 0 && item.functionSpace.join(',')) || ''
      })
      saveRecommendDetail(arr).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.showPageFlag = true
          this.getTableData(1, 10, false, this.otherFilters)
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/ .el-breadcrumb__inner{
  color: $qup-color-primary;
}
/deep/.el-table--mini{
  border: 1px solid #EBEEF5;
}
</style>
